package com.example.myBlogTest.controller;

import cn.hutool.core.bean.BeanUtil;
import com.example.myBlogTest.common.lang.Result;
import com.example.myBlogTest.entity.Blog;
import com.example.myBlogTest.exception.NotFoundException;
import com.example.myBlogTest.service.BlogService;
import com.example.myBlogTest.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Author: Lucy
 * Description:
 */
@RestController
@RequestMapping
public class BlogController {

    private BlogService blogService;

    public BlogController(BlogService blogService) {
        this.blogService = blogService;
    }

    @GetMapping("/blogs")
    public Result getBlogsByPage(@RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "5") int pageSize) {
        Page<Blog> blogs = blogService.getBlogsByPage(currentPage, pageSize);
        return Result.succ(blogs);
    }

    @GetMapping("/blog/{id}")
    public Result getBlogById(@PathVariable Long id) {
        try {
            Blog blog = blogService.findById(id);
            return Result.succ(blog);
        } catch (NotFoundException e) {
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/blog/edit")
    public Result editBlog(@Validated @RequestBody Blog blog) {
        Blog tempBlog;
        if(blog.getId() != null) {
            tempBlog = blogService.findById(blog.getId());
            Assert.isTrue(tempBlog.getUserId().longValue() == ShiroUtil.getProfile().getId().longValue(), "没有权限编辑");
        }else {

            tempBlog = new Blog();
            tempBlog.setUserId(ShiroUtil.getProfile().getId());
            tempBlog.setCreated(LocalDateTime.now());
            tempBlog.setStatus(0);
        }

        BeanUtil.copyProperties(blog, tempBlog, "id", "userId", "created", "status");
        blogService.saveOrUpdate(tempBlog);

        return Result.succ(null);
    }

}
